package demo.reflect;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

/**
 * getConstructors : 所有公有的构造方法
 * getDeclareConstructors: 获取所有的构造方法，包含公有、私有、受保护的
 *
 *
 *
 * @author weiyuewen 2020/6/9 16:23
 */


public class ConstructorCollector {

    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
        System.out.println("=====================公有构造方法==================");
        Class clazz = Class.forName("demo.reflect.ReflectTarget");
        Constructor[] conArray = null;
        //获取所有公有的构造方法
        conArray = clazz.getConstructors();
        for (Constructor c:conArray){
            System.out.println(c);
        }

        //2 获取所有的构造方法
        System.out.println("=====================所有构造方法==================");
        conArray = clazz.getDeclaredConstructors();
        for (Constructor c:conArray){
            System.out.println(c);
        }

        //获取单个带参数的构造方法
        System.out.println("=====================带参方法==================");
        Constructor con = null;
        con = clazz.getConstructor(String.class, int.class);
        System.out.println("con = " + con);

        //获取私有的带参数构造方法
        System.out.println("=====================私有构造方法==================");
        con = clazz.getDeclaredConstructor(int.class);
        System.out.println("private con = " + con);

        System.out.println("=====================调用私有构造方法创建实例==================");
        //暴力访问，忽略访问修饰符
        con.setAccessible(true);
        ReflectTarget reflectTarget = (ReflectTarget) con.newInstance(1);

    }

}
